package com.eregg.learn.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * 当服务器端收到客户端发送的数据时候调用
 */
public class FirstServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //接收客户端数据
        ByteBuf byteBuf = (ByteBuf)msg;
        System.out.println(String.format("[%s] 服务端读到数据 -> %s", new Date(), byteBuf.toString(Charset.forName("utf-8"))));

        //回复客户端数据
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes("欢迎订阅我的微信公众号\r\n".getBytes(Charset.forName("utf-8")));
        ctx.channel().writeAndFlush(buffer);
    }
}
